<?php

namespace App\Repositories;

use App\Models\TaobaoOrder;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class TaobaoOrderRepository
{
    protected $client;
    protected $appKey;
    protected $appSecret;

    public function __construct()
    {
        $this->client = new Client();
        $this->appKey = config('services.taobao.app_key');
        $this->appSecret = config('services.taobao.app_secret');
    }

    /**
     * 获取淘宝客服务商订单
     *
     * @param string $startTime 查询开始时间 (格式: Y-m-d H:i:s)
     * @param string $endTime 查询结束时间 (格式: Y-m-d H:i:s)
     * @param int $queryType 查询时间类型 (1:淘客订单创建时间, 2:淘客付款时间, 3:淘客结算时间)
     * @param string $session 用户授权session
     * @param int|null $tkStatus 订单状态 (12:付款, 13:关闭, 14:确认收货, 3:结算成功)
     * @param int $pageNo 页码
     * @param int $pageSize 每页大小
     * @param string|null $positionIndex 位点标记
     * 
     * @return array
     */
    public function getScOrders(
        string $startTime,
        string $endTime,
        int $queryType,
        string $session,
        ?int $tkStatus = null,
        int $pageNo = 1,
        int $pageSize = 20,
        ?string $positionIndex = null
    ): array {
        // 验证时间跨度 ≤24小时
        if (Carbon::parse($endTime)->diffInHours(Carbon::parse($startTime)) > 24) {
            throw new \InvalidArgumentException('时间跨度不能超过24小时');
        }

        $params = [
            'method' => 'taobao.tbk.sc.order.details.get',
            'app_key' => $this->appKey,
            'session' => $session,
            'timestamp' => now()->format('Y-m-d H:i:s'),
            'format' => 'json',
            'v' => '2.0',
            'sign_method' => 'md5',
            'start_time' => $startTime,
            'end_time' => $endTime,
            'query_type' => $queryType,
            'page_no' => $pageNo,
            'page_size' => $pageSize,
        ];

        if ($tkStatus) {
            $params['tk_status'] = $tkStatus;
        }

        if ($positionIndex) {
            $params['position_index'] = $positionIndex;
        }

        // 生成签名
        ksort($params);
        $signString = $this->appSecret;
        foreach ($params as $k => $v) {
            $signString .= "$k$v";
        }
        $signString .= $this->appSecret;
        $params['sign'] = strtoupper(md5($signString));

        try {
            $response = $this->client->post('https://eco.taobao.com/router/rest', [
                'form_params' => $params,
                'timeout' => 15
            ]);

            $result = json_decode($response->getBody(), true);
            
            return $result['tbk_sc_order_details_get_response']['data'] ?? [];
        } catch (\Exception $e) {
            Log::error('淘宝客订单查询失败', [
                'error' => $e->getMessage(),
                'params' => $params
            ]);
            
            return [];
        }
    }

    /**
     * 处理API响应并保存订单到数据库
     *
     * @param array $response
     * @return int 保存的订单数量
     */
    public function processAndSaveOrders(array $response): int
    {
        $orders = $response['results']['publisher_order_dto'] ?? [];
        $savedCount = 0;

        foreach ($orders as $orderData) {
            try {
                // 转换时间格式
                $orderData['click_time'] = $this->normalizeDateTime($orderData['click_time']);
                $orderData['tb_paid_time'] = $this->normalizeDateTime($orderData['tb_paid_time']);
                $orderData['tk_create_time'] = $this->normalizeDateTime($orderData['tk_create_time']);
                $orderData['tk_paid_time'] = $this->normalizeDateTime($orderData['tk_paid_time']);
                $orderData['modified_time'] = $this->normalizeDateTime($orderData['modified_time']);

                // 转换金额类型
                $moneyFields = [
                    'item_price', 'alipay_total_price', 'pub_share_fee', 
                    'pub_share_pre_fee', 'total_commission_fee', 'subsidy_fee'
                ];
                
                foreach ($moneyFields as $field) {
                    $orderData[$field] = floatval($orderData[$field] ?? 0);
                }

                // 转换比率类型
                $rateFields = [
                    'income_rate', 'pub_share_rate', 'tk_total_rate', 
                    'total_commission_rate', 'subsidy_rate'
                ];
                
                foreach ($rateFields as $field) {
                    $orderData[$field] = floatval($orderData[$field] ?? 0);
                }

                // 使用 updateOrCreate 保存或更新订单
                TaobaoOrder::updateOrCreate(
                    ['trade_id' => $orderData['trade_id']],
                    $orderData
                );

                $savedCount++;
            } catch (\Exception $e) {
                Log::error('保存淘宝客订单失败', [
                    'trade_id' => $orderData['trade_id'] ?? null,
                    'error' => $e->getMessage(),
                    'data' => $orderData
                ]);
            }
        }

        return $savedCount;
    }

    /**
     * 标准化时间格式
     * 
     * @param string|null $dateTime
     * @return string|null
     */
    protected function normalizeDateTime(?string $dateTime): ?string
    {
        if (empty($dateTime) {
            return null;
        }

        // 处理 "--" 等特殊值
        if ($dateTime === '--') {
            return null;
        }

        // 尝试解析时间
        try {
            return Carbon::parse($dateTime)->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return null;
        }
    }
}
